require(['init'], function () {
  var roleId = location.href.urlToObj().id

  var ROLE_URL = '/api/authority/role/' + roleId
  var ALL_PERMISSION_URL = '/api/authority/permissions'
  var CUR_PERMISSION_URL = '/api/authority/rolePermissions/' + roleId


  function loadRoleInfo(data) {
    $('[name=title]').val(data.title)
    $('[name=intro]').val(data.intro)
    if(data.status) {
      $('[name="use"]').click()
    }
  }

  function parsePermissionData(data) {
    var initData = []
    $.each(data, function (i, item) {
      if(item.pid == 0) {
        initData.push($.extend({}, item, {sub: []}))
      } else {
        $.each(initData, function (j, value) {
          if(item.pid == value.id) {
            value.sub.push(item)
          }
        })
      }
    })
    return initData
  }

  function submit() {
    $('#js-save').on('click', function () {
      var ids = []
      $('.permission-list input:checked').each(function (i, item) {
        ids.push(Number(this.id.split('_')[1]))
      })

      var title=$('[name=title]').val();
      var intro=$('[name=intro]').val();
      if(title.trim()==""||intro.trim()==""){
        $('.form-control').blur();
        _Tips("字段填写不全！");
        return;
      }
      _Waiting.show();
      $.when(
        $.ajax({
          url: '/api/authority/rolePermissions',
          method: 'post',
          dataType: 'json',
          data: {
            roleid: roleId,
            permissionids: ids
          }
        }),
        $.ajax({
          url: '/api/authority/role/' + roleId,
          method: 'put',
          dataType: 'json',
          data: {
            title: title,
            intro: intro,
            status: $('[name=use]').prop('checked') ? 1 : 0
          }
        })
      )
      .done(function () {
        _Waiting.close();
        console.log(arguments[0]);
        console.log(arguments[1]);
        _Tips(i18next.t('info.savesuccessfully'))//保存成功
      })
      .fail(function () {
        _Waiting.close();
        _Tips(i18next.t('info.savefailed'))//保存失败
      })

      // ajaxMethod({
      //   url: '/api/authority/rolePermissions',
      //   method: 'post',
      //   data: {
      //     roleid: roleId,
      //     permissionids: ids
      //   },
      //   success: function (data, status) {
      //     console.log(1);
      //   }
      // })
    })
  }

  function loadAllPermissions(data) {
    var permissionList = parsePermissionData(data)
    var $perList = $('<ul class="permission-list"></ul>')
    $.each(permissionList, function (i, item) {
      var $li = $('<li></li>').appendTo($perList)
      var $item = $('<label class="title" for="id_'+ item.id +'"><input type="checkbox" id="id_'+ item.id +'"/><strong>'+ i18next.t(item.title) +'</strong></label>').appendTo($li)
      $item.on('change', function () {
        var $this = $(this)
        var checkFlag = $this.find('input').prop('checked')
        $this.nextAll('label').each(function (i, menu) {
          $(menu).find('input').prop('checked', checkFlag)
        })
      })

      $.each(item.sub, function (j, subItem) {
        var $subItem = $('<label class="menu" for="id_'+ subItem.id +'"><input type="checkbox" id="id_'+ subItem.id +'"/>'+ i18next.t(subItem.title) +'</label>').appendTo($li)
        $subItem.on('change', function () {
          var $this = $(this)

          var checkFlag = $this.find('input').prop('checked')
          if(checkFlag) {
            $this.prevAll('.title').find('input').prop('checked', true)
            return
          }

          var listCheck = false
          for (var i = 1, $siblings = $this.siblings(); i < $siblings.length; i++) {
            var $curItem = $($siblings[i])
            if($curItem.find('input').prop('checked')) {
              listCheck = true
              break;
            }
          }

          if(listCheck) {
            $this.prevAll('.title').find('input').prop('checked', true)
          } else {
            $this.prevAll('.title').find('input').prop('checked', false)
          }
        })
      })
    })

    $('#permissionCover').append($perList)
    $('#js-save').show()
  }

  function loadCurPermissions(data) {
    $.each(data, function (i, item) {
      $('.permission-list').find('#id_'+ item.id +'').prop('checked', true)
    })
  }

  $.when(
    $.ajax(ROLE_URL),
    $.ajax(ALL_PERMISSION_URL),
    $.ajax(CUR_PERMISSION_URL)
  ).done(function () {
    var cbFnArr = [
      loadRoleInfo,
      loadAllPermissions,
      loadCurPermissions
    ]

    var resArr = [].slice.call(arguments,0,3)
    $.each(resArr, function (i, curRes) {
      if(curRes[1] == 'success') {
        cbFnArr[i](curRes[0].data)
      }
    })

    submit()
  })

})
